<template>
  <basic-container>
    <el-tabs v-model="tabActiveName" @tab-click="handleClick">
      <el-tab-pane label="卖家打款记录" name="first">
      </el-tab-pane>
      <el-tab-pane label="买家打款记录" name="second">
      </el-tab-pane>
    </el-tabs>
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :table-loading="loading"
               :permission="permissionList"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :page="page"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <!-- 自定义添加搜索条件  按日期搜索  -->
      <template slot="search">
        <el-col  :span="12">
          <el-form-item label="打款时间" style="display: inline-block;width: 50%;">
            <el-date-picker placeholder="开始时间" value-format="yyyy-MM-dd" v-model="beginPayTime" type="date" size="small">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="至"　label-width="40px" style="display: inline-block;width: 50%;">
            <el-date-picker placeholder="结束日期" @change="getTime" value-format="yyyy-MM-dd" v-model="endPayTime" type="date" size="small">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </template>
      <template slot="searchMenu">
        <el-button type="primary" size="mini" @click="outExcel">打款记录导出</el-button>
      </template>
      <template slot="searchMenu">
        <el-upload action="/account/withDrawRecord/inExcel"
                   name="file"
                   :show-file-list="false"
                   :before-upload="beforeUpload"
                   :on-success="handleSuccess"
                   :on-error="handleError"
                   :headers="myHeaders">
          <el-button style="margin-left: 10px" type="primary" size="mini">导入未打款记录</el-button>
        </el-upload>
      </template>
      <!-- 审核按钮  -->
      <template slot-scope="{row}"
                slot="menu">
          <el-button type="primary"
                     size="small"
                     plain
                     v-if="row.payStatus==1"
                     @click.stop="getDetail(row)" v-has="'/mall-cloud-account/withDrawRecord/detail'">打款</el-button>
          <el-button type="primary"
                     size="small"
                     plain
                     v-if="row.payStatus==0"
                     @click.stop="getDetail(row)" v-has="'/mall-cloud-account/withDrawRecord/detail'">查看</el-button>
      </template>
    </avue-crud>


    <el-drawer title="记录详情" :visible.sync="dialogTableVisible" size="70%" :wrapperClosable="false"
               :show-close="false">
      <avue-form ref="payCommit"
                 v-model="obj"
                 :option="optionView">
        <template slot="menuForm">
          <el-button type="primary" size="mini"  v-if="obj.newPayStatus==1" :loading="loadBtn" @click="commitCheck(obj.id,obj.payStatus,obj.payRemark)" v-has="'/mall-cloud-account/withDrawRecord/withDrawCarryOut'">提 交</el-button>
          <el-button size="mini" @click="cancel(obj.newPayStatus)">取 消</el-button>
        </template>
      </avue-form>
    </el-drawer>

  </basic-container>
</template>

<script>
    import {
        getPayList,
        getWithDrawRecordDetail,
        withDrawCarryOut
    } from "@/api/account/userAccount/adminCommitPayment";

    import { mapGetters } from "vuex";
    import {getToken} from '@/util/store';
    var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
    var CHECKDIC = [{
        label: '打款',
        value: 0,
    }]
    export default {
        data () {
            return {
                myHeaders: { Authorization: getToken() },
                tabActiveName: 'first', //tab页切换
                beginPayTime: '',
                endPayTime: '',
                loadBtn:false,
                deleteList: [], //全选的删除
                form: {},
                obj:{},
                arroyAllDict:{},
                query: {
					uaType : 2
				},
                loading: true,
                rolesTree: [],
                rolesKeys: [],
                box: false,
                dialogTableVisible: false,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                option: {
                    align: 'center',
                    size: 'mini',
                    tip: false,
                    border: true,
                    index: false,
                    selection: false,
                    viewBtn: false,
                    delBtn: false,
                    addBtn: false,
                    editBtn:false,
                    rowKey: 'id',
                    height: 'auto',
                    // calcHeight: 380,
                    menuWidth: 100,
                    searchMenuSpan:6,
                    column: [
                        {
                            label: "账户名称",
                            prop: "uaAccountName",
                            fixed: true,
                            search: true,
                        },
                        {
                            label: "提现金额",
                            prop: "amount",
                            fixed: true,
                        },
                        //暂时隐藏掉
                        // {
                        //     label: "服务费",
                        //     prop: "serviceAmount",
                        //     fixed: true,
                        // },
                        {
                            label: "提现渠道",
                            prop: "payWay",
                            fixed: true,
                            dicData: Dict.payWayEnum,
                        },
                        {
                            label: "提现账户",
                            prop: "account",
                            fixed: true,
                            search: true,
                        },
                        {
                            label: "开户行",
                            prop: "accountName",
                            fixed: true,
                        },
                        {
                            label: "银行卡号",
                            prop: "creditCardNumber",
                            fixed: true,

                        },
                        {
                            label: "真实姓名",
                            prop: "accountUsername",
                            fixed: true,

                        },
                        {
                            label: "打款人",
                            prop: "payManName",
                            fixed: true,
                        },
                        {
                            label: "打款时间",
                            prop: "payTime",
                            fixed: true,
                        },
                        // {
                        //     label: "打款描述",
                        //     prop: "payRemark",
                        //     fixed: true,
                        // },
                        {
                          label: "打款状态",
                          prop: "payStatus",
                          fixed: true,
                          search: true,
                          type: 'select',
                          dicData: Dict.payStatusEnum,
                        }
                    ]
                },
                optionView: {
                    size: "samll",
                    mock: false,
                    submitBtn: false,
                    emptyBtn: false,
                    menuPostion: 'center',
                    labelWidth: '100',
                    group:[
                        {
                            label: '基本信息',
                            prop: 'group0',
                            column: [
                                {
                                    placeholder:"账户名称",
                                    label: "账户名称",
                                    prop: "uaAccountName",
                                    fixed: true,
                                    disabled:true,
                                    display:true,
                                },
                                {
                                  placeholder:"提现账户",
                                  label: "提现账户",
                                  prop: "account",
                                  fixed: true,
                                  disabled:true,
                                  display:true,
                                },
                                {
                                    placeholder:"提现金额",
                                    label: "提现金额",
                                    prop: "amount",
                                    fixed: true,
                                    disabled:true,
                                    display:true,
                                },
                                //暂时去掉
                                // {
                                //     label: "服务费",
                                //     prop: "serviceAmount",
                                //     fixed: true,
                                //     disabled:true,
                                // },
                                {
                                    placeholder:"未选择",
                                    label: "提现渠道",
                                    prop: "payWay",
                                    fixed: true,
                                    type:'select',
                                    disabled:true,
                                    dicData: Dict.payWayEnum,
                                    display:true,
                                },
                                {
                                  placeholder:"申请原因",
                                  label: "申请原因",
                                  prop: "remark",
                                  type: 'textarea',
                                  disabled:true,
                                  fixed: true,
                                  value:false,
                                  display:true,
                                },
                                {
                                    placeholder:"打款人",
                                    label: "打款人",
                                    prop: "payManName",
                                    fixed: true,
                                    disabled:true,
                                    display:true,
                                },
                                {
                                    placeholder:"打款时间",
                                    label: "打款时间",
                                    prop: "payTime",
                                    fixed: true,
                                    disabled:true,
                                    display:true,
                                },
                                {
                                  placeholder:"打款描述",
                                  label: "打款描述",
                                  prop: "payRemark",
                                  type: 'textarea',
                                  disabled:true,
                                  fixed: true,
                                  value:false,
                                  display:true,
                                }
                            ]
                        },
                        {
                            label: '打款',
                            prop: 'group1',
                            column: [
                                {
                                    label: "打款",
                                    prop: "payStatus",
                                    type: 'radio',
                                    row: true,
                                    dicData: CHECKDIC,
									rules:[{
										required:true,
										message:'请勾选打款选项',
										trigger: "blur"
									}]
                                },
                                {
                                    label: "打款描述",
                                    prop: "payRemark",
                                    type: 'textarea',
                                    display:true,
                                    fixed: true,
                                    value:false,
                                    placeholder:"打款描述",
                                }
                            ]
                        }
                    ],

                },
                data: []
            };
        },
        watch:{
            'obj.newPayStatus'(){
                if(this.obj.newPayStatus == 1){
                    this.optionView.group[1].column[1].display = true
                }
                else{
                    this.optionView.group[1].column[1].display = false
                }
            }
        },
        computed: {
            ...mapGetters(["permission", 'userInfo']),
            permissionList () {
                return {
                    editBtn: this.vaildData(this.permission["/mall-cloud-account/withDrawRecord/editItem"], false)
                };
            },
        },
		created(){
			if(localStorage.getItem("tabActiveName")){
				this.tabActiveName=localStorage.getItem("tabActiveName")
			}
		},
        methods: {
          outExcel() {
            let token = getToken();
            let uaAccountName = this.query.uaAccountName === undefined ? "" : this.query.uaAccountName;
            let account = this.query.account === undefined ? "" : this.query.account;
            let payStatus = this.query.payStatus === undefined ? "" : this.query.payStatus;
            let beginPayTime = this.query.beginPayTime === undefined ? "" : this.query.beginPayTime;
            let endPayTime = this.query.endPayTime === undefined ? "" : this.query.endPayTime;
            let uaType = this.query.uaType === undefined ? "" : this.query.uaType;
            window.location.href = '/account/withDrawRecord/outExcel?token=' + token + '&uaAccountName=' + uaAccountName + '&account=' +
                    account + '&payStatus=' + payStatus + '&beginPayTime=' + beginPayTime + '&endPayTime=' + endPayTime + '&uaType=' + uaType;
          },
          //上传文件之前进行格式校验
          beforeUpload(file) {
            const isXLS = file.name.split(".")[1];
            if (isXLS === "xls"){
              return true;
            }
            const isXLSX = file.name.split(".")[1];
            if (isXLSX === "xlsx"){
              return true;
            }
            this.$message.error('上传的文件只能是xls或xlsx格式，推荐上传在本页面导出的未打款记录信息');
            return false;
          },
          // 文件上传成功时的钩子
          handleSuccess(res, file, fileList) {
            this.$notify.success({
              title: '成功',
              message: `文件上传成功`
            });
          },
          // 文件上传失败时的钩子
          handleError(err, file, fileList) {
            this.$notify.error({
              title: '错误',
              message: `文件上传失败`
            });
          },
            handleClick(tab) {
                //tab页切换
				if(localStorage.getItem("tabActiveName")){
					localStorage.removeItem("tabActiveName")
				}
                if (tab.name == "first") {
					this.$refs.crud.searchReset()
					this.query={}
                    this.query.uaType = 2; //店铺申请记录
                    this.page.currentPage=1
                    this.onLoad(this.page);
                } else if (tab.name == "second") {
					this.$refs.crud.searchReset()
					this.query={}
                    this.query.uaType = 1; //用户申请记录
                    this.page.currentPage=1
                    this.onLoad(this.page);
                }
            },
            getTime() {
                if(this.beginPayTime&&this.endPayTime){
                	if (this.beginPayTime > this.endPayTime) {
                	  this.$message({
                	    type: "error",
                	    message: "结束时间不能小于开始时间"
                	  });
                	  this.endPayTime = ''
                	  return
                	}
                }
            },

            rowSave (row, loading, done) {
                row.position = row.positionIds;
                row.deptName = row.$deptId;
                row.repassword = row.password;
                add(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            rowUpdate (row, index, loading, done) {
                row.position = row.positionIds;
                update(row).then(() => {
                    loading();
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                }, error => {
                    done();
                    console.log(error);
                });
            },
            searchReset () {
                this.query = {};
                if (this.tabActiveName == "first") {
                    this.query.uaType = 2; //店铺申请记录
                } else if (this.tabActiveName == "second") {
                    this.query.uaType = 1; //用户申请记录
                }
                this.beginPayTime = ''
                this.endPayTime = ''
                this.onLoad(this.page);
            },
            searchChange (params,done) {
                // params.status = 1;
                this.page.currentPage=1
				if(this.beginPayTime&&this.endPayTime){
					if (this.beginPayTime > this.endPayTime) {
					  this.$message({
					    type: "error",
					    message: "结束时间不能小于开始时间"
					  });
					  this.endPayTime = ''
					  return
					}
				}

                params.beginPayTime = this.beginPayTime
                params.endPayTime = this.endPayTime
                console.log(params)
                this.query = params;
                this.onLoad(this.page, params,done);
            },
            currentChange (currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange (pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange () {
                this.onLoad(this.page);
            },
            onLoad (page, params = {},done) {
              params.noUntreatedAndRefuse=true;//不查询未通过和拒绝的
              //adminWithDrawRecord.vue（提现审核界面）文件中点击去打款按钮会传递这个参数，如果用路由自带的传参方式会有打开多个tab页的问题，所以暂时这样处理
              var recordId=localStorage.getItem("record_to_payment_id");
              if(recordId){
                  this.optionView.group[1].display = true
                  getWithDrawRecordDetail(recordId).then(res => {
                    if(done){
                      done();
                    }
                    if(res.data.code == 200){
                      this.obj = res.data.data;
                      this.obj.newPayStatus = res.data.data.payStatus;
                      console.log(this.obj)
                      this.dialogTableVisible = true
                    }else{
                      this.$message({
                        message: res.data.message,
                        type: 'warning'
                      });
                      return;
                    }
                  });
              }else{
                  this.loading = true;
                  if (this.tabActiveName == "first") {
                    this.query.uaType = 2; //店铺申请记录
                  } else if (this.tabActiveName == "second") {
                    this.query.uaType = 1; //用户申请记录
                  }
                  getPayList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    if(done){
                      done();
                    }
                    this.loading = false;
                    const data = res.data;
                    this.page.total = data.count;
                    let newData=[];
                    if(data.data.length>0){
                      for(let i=0;i<data.data.length;i++){
                        if(data.data[i].status == 1 || data.data[i].status == 2 || data.data[i].status == 4){
                          if(data.data[i].payStatus == 0 || data.data[i].payStatus == 1){
                            newData.push(data.data[i])
                          }
                        }
                      }
                    }
                    this.data =newData;
                  });
              }
            },
            //打开抽屉
            //0，已打款 1，未打款
            getDetail(row){
              console.log(this.optionView.group[0].column)
                this.loadBtn=false
                if(row.payStatus == 0){
                    this.optionView.group[1].display = false;
                }
                else if(row.payStatus == 1){
                    this.optionView.group[1].display = true;
                }
              //0，未处理 1，审核通过  2，审核拒绝  3，未打款  4，已完成
                if(row.status == 4){
                  this.optionView.group[0].column[5].display = true;//打款人
                  this.optionView.group[0].column[6].display = true;//打款时间
                  this.optionView.group[0].column[7].display = true;//打款备注
                }
                else {
                  this.optionView.group[0].column[5].display = false;
                  this.optionView.group[0].column[6].display = false;
                  this.optionView.group[0].column[7].display = false;//打款备注
                }
                getWithDrawRecordDetail(row.id).then(res => {
                    if(res.data.code == 200){
                        this.obj = res.data.data;
                        this.obj.payRemark = res.data.data.payRemark;
                        this.obj.newPayStatus = res.data.data.payStatus;
                        console.log(this.obj)
                        this.dialogTableVisible = true
                    }else{
                        this.$message({
                            message: res.data.message,
                            type: 'warning'
                        });
                        return;
                    }
                });
            },
            commitCheck(id,payStatus,payRemark){
                this.loadBtn=true
                if(payStatus==0){
                  if(payRemark){
                    if(payRemark.length>100){
                      this.$message({
                        type: "error",
                        message: "打款描述最多输入100个字符"
                      });
                      this.loadBtn=false
                      return;
                    }
                  }
                  //提交打款
                  withDrawCarryOut(id,payStatus,payRemark).then(res => {
                    if(res.data.code == 200){
                      this.dialogTableVisible = false
                      this.$message({
                        type:'success',
                        message:'操作成功!'
                      })
                      localStorage.removeItem("record_to_payment_id");
                      this.onLoad(this.page, this.query);
                    }
                  });
                }
                else {
                    this.$message.error("请勾选打款选项");
                    this.loadBtn=false
                    return;
                }
            },
            cancel(newPayStatus){
				if(localStorage.getItem("tabActiveName")){
					localStorage.removeItem("tabActiveName")
				}
                this.dialogTableVisible = false;
                this.obj.remark = '';
                this.loadBtn=false;
                this.obj.payStatus = newPayStatus;
                localStorage.removeItem("record_to_payment_id");
                this.onLoad(this.page);
            },

        }
    };
</script>

<style>
</style>
